package com.jingyuan.biz.server.testnetty;

import com.jingyuan.biz.event.EventManager;
import com.jingyuan.biz.server.EventRQ;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.io.Serializable;
import java.nio.charset.Charset;
@ChannelHandler.Sharable
public class EchoServerHandler extends SimpleChannelInboundHandler<Serializable> {
    private EventManager eventManager;
    public EchoServerHandler(){

    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        EventRQ eventRQ=new EventRQ();
        eventRQ.setType(1);
        eventRQ.setMsg("welcome to server");
        ChannelFuture future = ctx.writeAndFlush(eventRQ);
        future.addListeners(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        future.addListener((f)->{
            if(f.isSuccess()){
                System.out.println("发生成功");
            }else{
                System.out.println("发送失败");
            }
        });
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Serializable msg) throws Exception {
        //ByteBuf in = (ByteBuf) msg;
        try {
//            StringBuffer buffer=new StringBuffer();
//            while (in.isReadable()) { // (1)
//                char c=(char) in.readByte();
//                buffer.append(c);
//                System.out.print(c);
//                System.out.flush();
//            }
            System.out.println(msg);
            EventRQ eventRQ=new EventRQ();
            eventRQ.setMsg(((EventRQ)msg).getMsg());
            eventRQ.setType(1);
            ctx.writeAndFlush(eventRQ);
        } finally {
            //ReferenceCountUtil.release(msg); // (2)
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //super.channelReadComplete(ctx);
//        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
//                .addListener(ChannelFutureListener.CLOSE);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}
